package top.eggcode.plugins.session;

import org.apache.commons.lang3.StringUtils;
import top.eggcode.common.mvc.HttpServletUtil;
import top.eggcode.plugins.session.manager.SessionManager;

/**
 * Title:
 * Description: TODO
 * Date: 2021/6/11 6:46
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public final class SessionHelper {

    private static SessionManager sessionManager;

    public static SessionManager getSessionManager() {
        return sessionManager;
    }

    public static void setSessionManager(SessionManager sessionManager) {
        SessionHelper.sessionManager = sessionManager;
    }

    public static Session getSession() {
        // 获取会话标识
        String sessionId = HttpServletUtil.getHeaderAttribute("Session-Id");

        if (StringUtils.isNotBlank(sessionId) && sessionManager.isValid(sessionId)) {
            return new ProxySession(sessionManager, sessionId);
        } else {
            Session session = sessionManager.start();
            return new ProxySession(sessionManager, session.getId());
        }

    }

    public static boolean isAuthenticated(String sessionId) {
        Session session = SessionHelper.getSessionManager().getSession(sessionId);

        String principal = null;

        // session不为空
        if (session != null) {
            principal = (String) session.getAttribute("principal");
            return principal != null;
        }

        return false;
    }
}
